package com.view;

import com.pojo.CodeFile;
import com.pojo.TableInfo;
import com.service.GeneratorService;
import org.apache.commons.collections.CollectionUtils;

import javax.swing.*;
import java.util.List;

public class GeneratorView extends JFrame {

    private static final long serialVersionUID = 1L;

    JPanel buttons = new JPanel(); // 按钮组
    JTextArea textArea = new JTextArea(); // 日志打印台

    private GeneratorService generatorService = new GeneratorService();

    public GeneratorView() {
        super("代码生成器");
        setLayout(null); // 主窗体忠组件的绝对位置 布局器
        setBounds(500, 100, 700, 700);
        this.init();
    }

    private void init() {
        // *************** 按钮组 ************ //
        buttons.setBounds(0, 0, 700, 130);
        super.add(buttons);
        final JButton getALlTablesButton = new JButton("所有表");
        final JButton generateCodeButton = new JButton("生成代码");
        buttons.add(getALlTablesButton);
        buttons.add(generateCodeButton);
        getALlTablesButton.addActionListener(e -> {
            textArea.setText("表名         表注释\n");
            for (TableInfo table : generatorService.getTables()) {
                textArea.append(String.format("%-10s\t%s\n", table.getTableName(), table.getTableComment()));
            }
        });
        generateCodeButton.addActionListener(e -> {
            String tableName = JOptionPane.showInputDialog("输入表名: ");
            while (buttons.getComponentCount() > 2)
                buttons.remove(buttons.getComponentCount() - 1);
            List<CodeFile> list = generatorService.generateCode(tableName);
            if (CollectionUtils.isEmpty(list)) {
                textArea.setText("生成失败");
                return;
            }
            textArea.setText("生成成功");
            for (CodeFile codeFile : list) {
                JButton button = new JButton(codeFile.filename);
                buttons.add(button);
                button.addActionListener(ee -> {
                    textArea.setText(codeFile.code);
                });
            }
            buttons.updateUI();
        });

        // *************** 日志打印台 ************ //
        textArea.setLineWrap(true); // 自动换行
        textArea.setEditable(true);
        JScrollPane textAreaPanel = new JScrollPane(textArea);
        textAreaPanel.setBounds(10, 130, 665, 520);
        super.add(textAreaPanel);

        super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时结束程序
        super.setVisible(true);
    }
}
